import Taro from '@tarojs/taro'
import { set as setGlobalData, get as getGlobalData } from '../static/js/global_data'
import api from './api'
import base from './../static/js/base'

module.exports = {
    changeCar,
    payToMerchants,
    payment,
}
// 加入、减去购物车 800b   减少、编辑购物车 801
function changeCar(param,callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    let str = ``
    let params = {
        bNo: param.bNo ? param.bNo : '801',
        gid: param.good.ID || param.good.N_GOODS_ID,
        num: param.num,
        mkid: param.mkid ? param.mkid : '', //促销活动编号
        mkcid: param.mkcid ? param.mkcid : '', //促销活动类型(1分时促销 2秒杀 3立减 4全场折扣 5积分活动)
        mebno: userInfo.C_MB_NO,
    };
    if (bNo == '801') { //减少购物车
        str = `mebno&gid&num&mkid&mkcid&ShopNo`
    } else { //加入购物车 800b
        str = `gid&num&mkid&mkcid&mebno&ShopNo`
        params['ljgm'] = param.ljgm ? param.ljgm : 0  //0:加入购物车1:立即购买 默认加入购物车
    }
    console.log(params)
    api.get(str, params).then((res) => {
        base.showToast(res.msg)
        if (callback) { callback(res) }
    }).catch((err) => {
        base.showToast(err.msg, 'none')
    })
}
// 删除购物车
function delCart(cartids, callback) {
    const str = `cartids&ShopNo`
    const params = {
        bNo: 803,
        cartids: cartids,
    }
    api.get(str, params, (res) => {
        if (callback) { callback(res) }
    })
}
// 获取购物车数量  805
function getCartNum(that,callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const str = `mebno&ShopNo`
    const params = {
        bNo: 805,
        mebno: userInfo.C_MB_NO,
    }
    api.get(str, params, function (res) {
        if(callback){callback(res)}
        that.setState({
            cartNum: res.goodsnum
        })
    })
}
//  获取用户购物车列表 802  获取部分购物车列表
function getUserCart(that, cids, callback) {
    let str = cids ? `mebno&cids&ShopNo` : `mebno&ShopNo`
    const userInfo = Taro.getStorageSync('userInfo')
    let params = {
        bNo: 802,
        mebno: userInfo.C_MB_NO,
        // isactive: '1'
    }
    if (cids) {
        params['cids'] = cids
    }
    api.get(str, params, function (res) {
        // console.log(res)
        if (cids) {
            if (callback) { callback(res) }
        } else {
            // that.setState({ cartList: res.cart })
            if (callback) { callback(res.cart, res) }
        }
    }, function (res) {
        if (cids) {
            if (callback) { callback(res) }
        } else {
            // that.setState({ cartList: res.cart })
            if (callback) { callback(res.cart, res) }
        }
    })
}
// 设置购物车、分类商品列表 加减购物车数量
function setCartList(that, pages, index, bNo, types, callback) {
    let lists;
    if (pages == 'cart') { //购物车页面
        lists = that.state.cartList
    }
    if (pages == 'goodList') { //商品分类列表页面
        lists = that.state.goodList
    }
    if (bNo == '800b') {// +
        if (lists[index].STOCK <= lists.N_NUM) {
            base.showToast('商品库存不足了！')
            return
        }
    }
    let nums = types == 'add' ? '1' : lists[index].N_NUM - 1;
    changeCar(that, bNo, lists[index], nums, '0', (res) => {
        lists[index].N_NUM = res.cartnum
        let gid = lists[index].ID || lists[index].N_GOODS_ID
        let cartId = ''
        if (res.cartnum == 0 && bNo == '801') {
            getUserCart(that, null, (res) => {
                res.map((item, i) => {
                    if (gid == item.N_GOODS_ID) {
                        cartId = item.N_OC_ID
                    }
                })
                if (cartId != '') {
                    delCart(cartId, (r) => {
                        if (pages == 'cart') {
                            base.showToast('删除' + r.msg)
                        }
                    })
                }
                if (pages == 'cart') {
                    lists.splice(index, 1)
                    if (callback) { callback(lists) }
                }
                if (pages == 'goodList') {
                    that.setState({ goodList: lists })
                    if (callback) { callback(lists) }
                }
            })
        } else {
            if (pages == 'cart') {
                if (callback) { callback(lists) }
            }
            if (pages == 'goodList') {
                that.setState({ goodList: lists })
                if (callback) { callback(lists) }
            }
        }
    })
}
// 订单详情展示
function getOrderDetail(that, cids, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    if (cids != '') {  //提交订单
        const str = `mebNo&shopNo&subOrderNo`
        // const params = {
        //     bNo: 808,
        //     mebno: userInfo.C_MB_NO,
        //     cids: cids,
        // }
        const params = {
            bNo: "GO0102",
            mebNo: userInfo.C_MB_NO,
            shopNo: getGlobalData('SHOP_NO'),
            subOrderNo: cids
        }
        api.get(str, params, (res) => {
            if (res.posmethod) { //配送方式
                let flagPost = 0
                res.posmethod.map((item, i) => {
                    if (item.n_isdefault == 1) {
                        that.state.psmethod = item.c_psname
                        flagPost++
                    }
                })
                if (flagPost == 0) {
                    res.posmethod[0].n_isdefault = 1
                    that.state.psmethod = res.posmethod[0].c_psname
                }
            }
            if (res.Selflift) { // 门店自提列表
                res.Selflift.map((item, i) => {
                    item.def = i == 0 ? '1' : '0'
                })
            }
            // res.address = {C_ADDRESS : "新港中路397号",
            //         C_CITY : "广州市",
            //         C_CITY_CODE : "",
            //         C_COUNTY : "海珠区",
            //         C_MB_LONGITUDE : "113.325296,23.095369",
            //         C_MB_NAME : "张三",
            //         C_MB_NO : "1013755",
            //         C_MB_PHONE : "020-81167888",
            //         C_OPENID : null,
            //         C_PROVINCE : "广东省",
            //         C_SHOP_NO : "100276",
            //         C_ZIPCODE : "",
            //         N_ISDEFAULT : 1,
            //         N_MA_ID : 1713
            //     }

            // if (res.SaleActive) {
            //     res.SaleActive = JSON.parse(res.SaleActive)
            // }
            // if (res.address) {
            //     res.address.C_MB_LONGITUDE = res.address.C_MB_LONGITUDE.split(",")
            //     for (let i = 0; i < res.address.C_MB_LONGITUDE.length; i++) {
            //         if (typeof res.address.C_MB_LONGITUDE[i] == "string") {
            //             res.address.C_MB_LONGITUDE[i] = parseFloat(res.address.C_MB_LONGITUDE[i])
            //         }
            //     }
            //     that.setData({
            //         address: res.address,
            //         addid: res.address.N_MA_ID
            //     })
            // }
            // console.log("订单详情that.data.psmethod_lx: " + that.data.psmethod_lx)
            // //posmethodNo n_ps_lx	1商家配送 2骑士专送 3快递配送 4门店自提
            // if (!that.data.cart) {
            //     if (res.cart) {
            //         for (let i = 0; i < res.cart.length; i++) {
            //             res.cart[i].salemodel = null
            //             if (res.cart[i].saledata) {
            //                 for (let j = 0; j < res.cart[i].saledata.length; j++) {
            //                     if (res.cart[i].N_MARKING_CID == res.cart[i].saledata[j].SaleTypeNo) {
            //                         res.cart[i].salemodel = res.cart[i].saledata[j]
            //                     }
            //                 }
            //             }
            //         }
            //     }
            that.setState({
                cart: res.cart,
                posmethod: res.posmethod,
                psmethod: that.state.psmethod,
                postime: res.postime,
                selflift: res.Selflift, // 自提店铺地址列表
                selfliftSelect: res.Selflift[0], //当前选择的自提地址
                selfliftShow: that.state.psmethod == '上门自提' ? true : false, //上门自提列表是否显示
                address: res.address,//地址
                // checkedIndex: that.data.checkedIndex,
                // psmethod_lx: that.data.psmethod_lx
            }, () => {
                if (callback) { callback() }
            })
        })
    }
}
// 获取订单金额
function getOrderPrices(that, callback) {
    const userInfo = Taro.getStorageSync('userInfo')
    const params = {
        bNo: 420,
        mebno: userInfo.C_MB_NO,
        cids: that.state.cids, //购物车编号id
        yhqid: that.state.yhqid, //领取的优惠券id（n_mcr_id）
        psmethod: that.state.psmethod, //配送方式；数据类型：string（上门自提，骑士专送，快递配送，商家配送）
        isactive: that.state.isactive, //是否要参加促销活动(1参加，2不参加)
        isIntergral: that.state.intergralState, //积分 0不开启，1开启
        isBalance: that.state.balanceState, // 余额 0不开启，1开启
    }
    api.get('', params, (res) => {
        if (that.state.yhqid != '') {
            res.marketimg.map((item, i) => {
                item.select = that.state.yhqid == item.MarketingCId ? true : false
            })
        }
        that.setState({
            refresh: false,
            marketimg: res.marketimg, //优惠券列表
            postmoney: res.Youfei, //运费
            orderyprice: res.allmoney, //商品金额
            orderprice: res.ordermoney, //实付款
            cxuserIntergral: res.cxuserIntergral, //单商品活动积分
            Intergral: res.Intergral,
            IntergralMoney: res.IntergralMoney,
            balance: res.balance,
            dbje: res.dbje,
            // ShoppingCardid:"0",
            // ShoppingMoney:0,
            // code:"100",
            // cqsje:0,
            // goodscxje:5.58,
            // mallcxje:0,
            // psground:"1",
            // qsje:0,
            // zkje:0,
        })
        if (callback) { callback() }
    })
    // if (that.state.psmethod_lx == "骑士专送") {
    //    if (that.state.qspostmoney) {//骑士配送运费；数据类型：string
    //       params['qspostmoney'] = that.state.qspostmoney
    //    }
    // }
    // if (that.data.switchIntergral) {
    //    params['isIntergral'] = '1'
    // } else {
    //    params['isIntergral'] = '0'
    // }
    // if (that.data.switchBalance) {
    //    params['isBalance'] = '1'
    // } else {
    //    params['isBalance'] = '0'
    // }
    // if (that.data.saleids) {//	活动编号
    //    params['saleids'] = that.data.saleids
    // }
    // if (that.data.psmethod_lx == "商家配送" || that.data.psmethod_lx == "骑士专送") {
    //    if (that.data.addid) {//	地址id；数据类型：int
    //       params['addid'] = that.data.addid
    //    }
    //    console.log("that.data.addid: " + that.data.addid)
    // }
    // console.log("that.data.psmethod_lx: " + that.data.psmethod_lx)
    // console.log("that.data.addid: " + that.data.addid)
    // app.remote('', params, function (res) {
    //    console.log("420结算价格：")
    //    console.log(res)
    //    if (res.marketimg) {
    //       for (let i = 0; i < res.marketimg.length; i++) {
    //          res.marketimg[i].MarketingBeginTime = res.marketimg[i].MarketingBeginTime.replace(/\-/g, ".")
    //          res.marketimg[i].MarketingEndTime = res.marketimg[i].MarketingEndTime.replace(/\-/g, ".")
    //       }
    //    }
    //    if (!that.data.prices) {
    //       that.setData({
    //          totalBalance: res.balance,
    //          totalIntergral: res.Intergral,
    //          IntergralMoney: res.IntergralMoney
    //       })
    //    }
    //    if (that.data.psmethod_lx == "商家配送" || that.data.psmethod_lx == "骑士专送") {
    //       //psground  0不在配送范围，1在配送范围,-1无法取到配送距离
    //       var txt = ""
    //       if (that.data.psmethod_lx == "商家配送") {
    //          txt = "地址不在商家配送范围"
    //       } else {
    //          txt = "地址不在骑士专送配送范围"
    //       }
    //       if (res.psground == "0") {
    //          wx.showModal({
    //             title: '提示',
    //             content: txt,
    //             showCancel: false
    //          })
    //       }
    //       that.setData({
    //          psground: res.psground
    //       })
    //    } else {
    //       psground: null
    //    }
    //    that.setData({
    //       prices: res,
    //       marketimg: res.marketimg, //卡券
    //       isShow: true
    //    })
    //    console.log(that.data.isShow)
    //    if (callback) {
    //       callback()
    //    }
    //    wx.hideLoading()
    // })
}
// 付款到商家
function payToMerchants(param,callback,errback){
    let userInfo = Taro.getStorageSync('userInfo')
    const str = `mebno&ShopNo&amount&yhqstr&zpid`
    let params = {
        bNo: 423,
        mebno: userInfo.C_MB_NO,
        amount: param.amount,
        yhqstr: param&&param.yhqstr ? param.yhqstr : '',
        zpid: param&&param.zpid ? param.zpid : '',
        isBalance: param&&param.isBalance ? param.isBalance : 0, // 余额支付 1：使用 0：不使用
    }
    api.get(str,params).then((res) => {
        if(callback){callback(res)}
    }).catch((err) => {
        if(errback){errback(err)}
    })
}
// 支付
function payment(orderno, callback, failback, comback) {
    let env = process.env.TARO_ENV;
    if (env == 'weapp') {
        _weappPayment(orderno, callback, failback, comback)
    } else if (env == 'alipay') {
        console.log('alipay -------')
        _alipayPayment(orderno, callback, failback, comback)
    }
}
// 微信支付
function _weappPayment(orderno, callback, failback, comback) {
    const openid = Taro.getStorageSync('openid')
    const params = {
        bNo: 1501,
        orderno: orderno,
        openid,
        type: 1,
    }
    api.get('', params).then((err) => {
        console.log(err)
    }).catch((res) => {
        if (res.errCode == 0) {
            Taro.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
            })
            .then((data) => {
                console.log(data)
                base.showToast('支付成功')
                if (callback) { callback() }
                else {
                    setTimeout(function () {
                        Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${orderno}` })
                    }, 1000)
                }
            })
            .catch((fail) => {
                console.log(fail)
                if (fail.errMsg == "requestPayment:cancel" || fail.errMsg == "requestPayment:fail cancel") {
                    base.showToast('您取消支付了', 'none')
                    if (failback) { failback() }
                    else {
                        setTimeout(function () {
                            Taro.reLaunch({ url: '/pages/personal/personal' })
                        }, 1000);
                    }
                } else {
                    base.showModal(fail.msg)
                }
            })
        } else {
            base.showModal(res.msg, false, () => {
                if (comback) { comback() }
                else { Taro.reLaunch({ url: '/pages/personal/personal' }) }
            })
        }

        // console.log(err)
        // base.showModal(err.errMsg,null,() => {
        //     Taro.navigateBack()
        // })
        // Taro.hideLoading()
    })
}
// 支付宝支付
function _alipayPayment(orderno, callback, failback, comback) {
    const openid = Taro.getStorageSync('openid')
    const params = {
        OpenId: openid,
        OrderNo: orderno,
        type: 2
    }
    api.postAlipay('/CreateOrder',params).then((res) => {
        my.tradePay({
            tradeNO: res.data.tradeNO, // 调用统一收单交易创建接口
            success: (_res) => {
                console.log('tradeNO_res-----')
                console.log(_res)
                base.showToast(_res.memo)
                if(_res.resultCode == '9000'){
                    if (callback) { callback() }
                    else{
                        setTimeout(function () {
                            Taro.reLaunch({ url: `/pages/payResult/payResult?result=0&&orderno=${orderno}` })
                        }, 1000)
                    }
                }else{
                    if (failback) { failback() }
                    else{
                        setTimeout(function () {
                            Taro.reLaunch({ url: `/pages/personal/personal` })
                        }, 1000)
                    }  
                }  
            },
            fail: (_err) => {
                console.log('tradeNO_err-----')
                console.log(_err)
                if(failback){failback()}
                else{
                    my.alert({
                        content: JSON.stringify(_err),
                    });
                }
                Taro.hideLoading()
            },
            complete: () => {
            }
        });
    }).catch((err) => {
        console.log(err)
        base.showModal(err.msg, null,() => {
            Taro.reLaunch({
                url: '/pages/personal/personal'
            })
        })
    })
}


